"""配置管理模块.

本模块负责管理系统的所有配置项,包括:
- 数据库配置
- Redis配置
- Kafka配置
- API配置
- 评分系统配置
- 监控系统配置
"""

import os
from typing import Any, Dict, Optional

from dotenv import load_dotenv

# 加载环境变量配置文件
load_dotenv()

class Config:
    """配置类,用于管理系统设置."""
    
    # 数据库配置
    DB_HOST: str = os.getenv("DB_HOST", "localhost")
    DB_PORT: int = int(os.getenv("DB_PORT", "5432"))
    DB_NAME: str = os.getenv("DB_NAME", "crcs")
    DB_USER: str = os.getenv("DB_USER", "postgres")
    DB_PASSWORD: str = os.getenv("DB_PASSWORD", "")
    
    # Redis配置
    REDIS_HOST: str = os.getenv("REDIS_HOST", "localhost")
    REDIS_PORT: int = int(os.getenv("REDIS_PORT", "6379"))
    REDIS_DB: int = int(os.getenv("REDIS_DB", "0"))
    
    # Kafka配置
    KAFKA_BOOTSTRAP_SERVERS: str = os.getenv("KAFKA_BOOTSTRAP_SERVERS", "localhost:9092")
    KAFKA_TOPIC_PREFIX: str = os.getenv("KAFKA_TOPIC_PREFIX", "crcs")
    
    # API配置
    API_SECRET_KEY: str = os.getenv("API_SECRET_KEY", "your-secret-key-here")
    API_TOKEN_EXPIRE_MINUTES: int = int(os.getenv("API_TOKEN_EXPIRE_MINUTES", "30"))
    
    # 评分系统配置
    MIN_CREDIT_SCORE: int = int(os.getenv("MIN_CREDIT_SCORE", "0"))
    MAX_CREDIT_SCORE: int = int(os.getenv("MAX_CREDIT_SCORE", "1000"))
    SCORE_UPDATE_INTERVAL: int = int(os.getenv("SCORE_UPDATE_INTERVAL", "3600"))
    
    # 监控配置
    SENTRY_DSN: Optional[str] = os.getenv("SENTRY_DSN")
    PROMETHEUS_PORT: int = int(os.getenv("PROMETHEUS_PORT", "9090"))
    
    # 环境配置
    ENV: str = os.getenv("ENV", "development")
    
    @classmethod
    def get_database_url(cls) -> str:
        """获取数据库连接URL.
        
        Returns:
            str: SQLAlchemy格式的数据库连接URL
        """
        return f"postgresql://{cls.DB_USER}:{cls.DB_PASSWORD}@{cls.DB_HOST}:{cls.DB_PORT}/{cls.DB_NAME}"
    
    @classmethod
    def get_redis_url(cls) -> str:
        """获取Redis连接URL.
        
        Returns:
            str: Redis连接URL
        """
        return f"redis://{cls.REDIS_HOST}:{cls.REDIS_PORT}/{cls.REDIS_DB}"
    
    @classmethod
    def is_development(cls) -> bool:
        """检查是否为开发环境.
        
        Returns:
            bool: 是否为开发环境
        """
        return cls.ENV.lower() == "development"
    
    @classmethod
    def is_production(cls) -> bool:
        """检查是否为生产环境.
        
        Returns:
            bool: 是否为生产环境
        """
        return cls.ENV.lower() == "production"
    
    @classmethod
    def is_testing(cls) -> bool:
        """检查是否为测试环境.
        
        Returns:
            bool: 是否为测试环境
        """
        return cls.ENV.lower() == "testing"
    
    @classmethod
    def as_dict(cls) -> Dict[str, Any]:
        """将配置转换为字典格式.
        
        Returns:
            Dict[str, Any]: 配置字典
        """
        return {
            key: value for key, value in cls.__dict__.items()
            if not key.startswith("_") and isinstance(value, (str, int, float, bool))
        }